package book;

import constant.Constant;
import utils.AnalyzingBook;

import java.io.IOException;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.Arrays;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 刘国水
 * Date: 2025-04-01
 * Time: 22:27
 */
public class Library {
    //存储的书籍
    public Book[] books;
    //记录当前图书馆 有效的书 到底是几本
    public int bookCount;

    private static Library library;

    private AnalyzingBook analyzingBook = new AnalyzingBook();

    private Library() {
        //读
        loadAllBook();
    }

    public static Library getLibrary() {
        if (library == null) {
            library = new Library();
        }
        return library;
    }

    //写成一个独立的方法 后期 实时可以进行更新 查看 我们当前书架到底有多少本书
    private void loadAllBook() {
        try {
            //1.读取文件的书籍 到allBook 数组当中
            Book[] allBook = analyzingBook.loadObject(Constant.All_BOOK_FILE_NAME);
            //2.给当前书架 默认分配的大小是5
            books = new Book[Constant.CAPACITY];

            if (allBook == null) {
                bookCount = 0;
            } else {
                int allBookLen = allBook.length; //10 3
                if (allBookLen > books.length) {
                    books = new Book[allBookLen];
                }

                for (int i = 0; i < allBookLen; i++) {
                    books[i] = allBook[i];
                }
                //有效书籍
                bookCount = allBookLen;
            }


        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    //共用的方法
    public void searchBook() {
        System.out.println("查找图书");

    }

    public void displayBook() {
        System.out.println("显示图书");
        for (int i = 0; i < bookCount; i++) {
            System.out.println(books[i]);

        }

    }

    public void exit() {
        System.out.println("退出系统");
        System.exit(0);
    }

    public void addBook(Book book) {
        if (bookCount >= books.length) {
            System.out.println("图书馆已满，⽆法上架更多图书！");
            return;
        }
        //修改bookId为⾃增

        books[bookCount++] = book;
        book.setBookId(bookCount);
        //此时存储数据的时候 会把书籍对象全部存储，虽然部分属性没有输⼊赋值
        storeBook();
        System.out.println("图书 " + book.getTitle() + "上架成功！");

    }

    //存储图书到文件夹中
    private void storeBook() {
        try {
            analyzingBook.storeObject(books, Constant.All_BOOK_FILE_NAME);
        } catch (IOException e) {
            throw new RuntimeException();
        }

    }

    public Book searchById(int bookId) {
        for (int i = 0; i < bookCount; i++) {
            Book book = books[i];
            System.out.println(books[i]);
            if (book.getBookId() == bookId) {
                return book;
            }

        }
        return null;
    }

    public void updateBook(Book book) {

        int bookId = book.getBookId();
        //先找到该书是哪个下标
        int index = searchByIdReturnIndex(bookId);
        if (index == -1) {
            System.out.println("没有你要更新的图书，此时的ID为：" + bookId);
            return;
        }
        books[index] = book;
        storeBook();
        System.out.println("图书已经更新，文件已经写入，更新后的书籍为：");
        System.out.println(books[index]);
    }

    //根据bookId 返回 书籍索引位置
    private int searchByIdReturnIndex(int bookId) {
        loadAllBook();
        for (int i = 0; i < bookCount; i++) {
            Book book = books[i];
            if (book.getBookId() == bookId) {
                return i;
            }
        }
        return -1;
    }

    public void displayBooks() {
    }

    public void removeBook(int bookId) {
        int index = searchByIdReturnIndex(bookId);
        //开始删除 从当前位置的后边往前移动
        for (int i = index; i < bookCount - 1; i++) {
            books[i] = books[i + 1];
        }
        books[bookCount - 1] = null;
        storeBook();
        bookCount--;

    }

    public void borrowCount() {
        loadAllBook();
        for (int i = 0; i < bookCount; i++) {
            Book book = books[i];
            System.out.println("书名:"+book.getTitle()+
                    " 借阅次数："+book.getBorrowedCount());
        }

    }
    //查询最受欢迎的前n本书
    public void generateBook(int k) {
        //1. 加载已有的全部的书籍
        loadAllBook();
        //2.把所有书籍放在 临时数据 进⾏排序
        Book[] tmp = new Book[bookCount];
        for (int i = 0; i < bookCount; i++) {
            tmp[i] = books[i];
        }
        //2.1 开始排序
        Arrays.sort(tmp);
        //3. 把前k本书拷⻉到新数组 可以不定义临时数组，直接输出前K个就⾏
        Book[] generateBooks = new Book[k];
        for (int i = 0; i < k; i++) {
            generateBooks[i] = tmp[i];
        }
        //4.打印新数组
        System.out.println("最受欢迎书籍如下：");
        for (int i = 0; i < generateBooks.length; i++) {
            Book book = generateBooks[i];
            System.out.println("索引: " + i + " 书名：" + book.getTitle() + " 作者：" +
                    book.getTitle() + " 借阅次数：" + book.getBorrowedCount());
        }

    }

    public void checkInventoryStatus() {
        loadAllBook();
        for (int i = 0; i < bookCount; i++) {
            Book book = books[i];
            String status = book.isBorrowed() ? "已借出" : "在馆";
            System.out.println("书名："+book.getTitle()+" ⽬前状态："+status);
        }
    }

    public void checkAndRemoveOldBooks(Scanner scanner) {
        loadAllBook();
    // 获取当前时间戳
        long currentTimestamp = System.currentTimeMillis();
    // 将当前时间戳转换为 LocalDate
        LocalDate currentDate = Instant.ofEpochMilli(currentTimestamp)
                .atZone(ZoneId.systemDefault())
                .toLocalDate();
        boolean flg = false;
        for (int i = 0; i < bookCount; i++) {
            Book book = books[i];
            //获取当前书籍的上架时间
            LocalDate specifiedDate = book.getShelfDate();
            // 计算两个⽇期之间的差值（以年为单位）
            long yearsBetween = ChronoUnit.YEARS.between(specifiedDate,
                    currentDate);
            if(yearsBetween >= 1) {
                System.out.print("图书 " + book.getTitle() + " 已经上架超过⼀年，是否 移除？ (y/n)：");
                scanner.nextLine();
                String response = scanner.nextLine();
                if (response.equalsIgnoreCase("y")) {
                //确认删除调⽤remove⽅法进⾏删除
                    removeBook(i);
                    i--; // 因为后⾯的书已经向前移动，所以要重新检查当前索引位置
                }
                flg = true;
            }
        }
        if(!flg) {
            System.out.println("没有上架超过⼀年的图书！");
        }
    }

    public void borrowBook(int bookId) {
        loadAllBook();
        for (int i = 0; i < bookCount; i++) {
            Book book = books[i];
            if(book.getBookId()== bookId) {
                book.setBorrowed(true);
                book.incrementBorrowCount();
            }
        }
        storeBook();
    }
    //根据bookId 查找对应书籍

    public Book searchById(int bookId) {
        loadAllBook();
        for (int i = 0; i < bookCount; i++) {
            Book book = books[i];
            if(book.getBookId()==bookId) {
                return book;
            }
        }
        return null;
    }
    public void incrementBorrowCount() {
        this.borrowCount++;
    }
    public void decreaseBorrowCount() {
        this.borrowCount--;
    }
}

